package com.wg.core.utils;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.security.KeyStore;

/**
 * @author 少爷123
 */
public class SslUtil {
    private static volatile SSLContext sslContext = null;

    /**
     * 创建ssl 实例
     *
     * @param fileName PKCS12->pfx文件 JSK->jk文件
     * @param password 密码
     * @return SSLContext实例
     */
    public static SSLContext createSslContext(String fileName, String password) throws Exception {
        if (null == sslContext) {
            synchronized (SslUtil.class) {
                if (null == sslContext) {
                    KeyStore ks = KeyStore.getInstance(KeyType.getKeyType(fileName));
                    InputStream ksInputStream = ResourceUtil.getStream(fileName);
                    ks.load(ksInputStream, password.toCharArray());
                    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                    kmf.init(ks, password.toCharArray());
                    sslContext = SSLContext.getInstance("TLS");
                    sslContext.init(kmf.getKeyManagers(), null, null);
                }
            }
        }
        return sslContext;
    }

    public enum KeyType {
        PKCS12("PKCS12", "pfx"),
        JKS("JKS", "jks");
        private final String value;
        private final String extra;

        KeyType(String value, String extra) {
            this.value = value;
            this.extra = extra;
        }

        public static String getKeyType(String fileName) {
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (PKCS12.extra.equalsIgnoreCase(suffix)) {
                return PKCS12.value;
            } else if (JKS.extra.equalsIgnoreCase(suffix)) {
                return JKS.value;
            } else {
                throw new IllegalArgumentException(StrUtil.format("unkonw keytype. filename={}", fileName));
            }
        }

        public String getValue() {
            return value;
        }

        public String getExtra() {
            return extra;
        }
    }
}
